package com.qfedu.rocketmq01.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/14 10:04
 * @Modified:
 */
@Component
@RocketMQTransactionListener
@Slf4j
public class TranListener implements RocketMQLocalTransactionListener {
    //执行本地业务逻辑
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        Random random=new Random();
        int r=random.nextInt(3);
        RocketMQLocalTransactionState state;
        switch (r){
            case 0://提交
                state=RocketMQLocalTransactionState.COMMIT;break;
             case 1://回滚
                state=RocketMQLocalTransactionState.ROLLBACK;break;
            default:
                state=RocketMQLocalTransactionState.UNKNOWN;break;
        }
        log.info("事务消息的状态确认={}",r);
        return state;
    }

    //回查 如果事务状态为unkonwn 那么就会自动执行回查  间隔
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("事务消息回查-{}",message.getPayload());
        return RocketMQLocalTransactionState.COMMIT;
    }
}
